from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

# 帮我们直接运行此文件时，可以加载到上级目录的ui包
sys.path.append("../")

from ui.Ui_protocol_analyze import Ui_protocol_analyze


class protocol_analyze_Widget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_protocol_analyze()
        self.ui.setupUi(self)

        self.init_ui()

    def init_ui(self):
        self.ui.push_Button_jiexi.clicked.connect(self.f_jiexi_4g_up_temp_data)

    def f_jiexi_4g_up_temp_data(self):
        protocol_text = self.ui.lineEdit_4g_up_temp_data.text().strip()

        print(protocol_text)

        if not protocol_text:
            QMessageBox.warning(self, "警告", "请输入协议数据！")
            return

        # 转换为字节数组
        try:
            data = bytes.fromhex(protocol_text)
        except ValueError:
            QMessageBox.warning(self, "警告", "输入不是有效的十六进制字符串！")
            return

        # 验证首部
        if len(data) < 2 or data[0] != 0x55 or data[1] != 0xAA:
            QMessageBox.warning(self, "警告", "协议首部不正确！")
            return

        # 解析长度
        length = data[2]
        if len(data) != length:  # 首部2字节
            QMessageBox.warning(self, "警告", "数据长度不匹配！")
            return

        # 解析各个字段
        textEdit_4g_up_temp_data_result = []
        textEdit_4g_up_temp_data_result.append("=== 协议解析结果 ===")
        textEdit_4g_up_temp_data_result.append(f"首部: {data[0]:02X}{data[1]:02X}")
        #         格式	说明
        # {x}	十进制
        # {x:x}	小写十六进制，无前缀
        # {x:X}	大写十六进制，无前缀
        # 0x{x:x}	手动加 0x 前缀
        # {x:04x}	至少4位，不足补零（如 00ff）
        textEdit_4g_up_temp_data_result.append(
            f"长度:(0x{length:x})  10进制为：{length}"
        )
        textEdit_4g_up_temp_data_result.append(
            f"数据来源: {data[3]:02X} ({'4G主站采集' if data[3] == 0x05 else '未知'})"
        )
        textEdit_4g_up_temp_data_result.append(
            f"命令: {data[4]:02X} ({'读取温度数据' if data[4] == 0x01 else '未知'})"
        )
        textEdit_4g_up_temp_data_result.append(
            f"方向: {data[5]:02X} ({'上行' if data[5] == 0x01 else '下行'})"
        )
        textEdit_4g_up_temp_data_result.append(
            f"通信模式: {data[6]:02X} ({'4G' if data[6] == 0x02 else '未知'})"
        )
        textEdit_4g_up_temp_data_result.append(f"网关IMEI: {data[7:15].hex()}")
        textEdit_4g_up_temp_data_result.append(f"ICCID: {data[15:25].hex()}")
        textEdit_4g_up_temp_data_result.append(f"温度包数量: {data[25]}")

        # 输出到文本框
        self.ui.textEdit_4g_up_temp_data_result.setPlainText(
            "\n".join(textEdit_4g_up_temp_data_result)
        )

        # # 解析时间戳（BCD码）
        # year_bcd = data[35]
        # month_bcd = data[36]
        # day_bcd = data[37]
        # hour_bcd = data[38]
        # minute_bcd = data[39]
        # second_bcd = data[40]

        # year = (year_bcd >> 4) * 10 + (year_bcd & 0x0F)
        # month = (month_bcd >> 4) * 10 + (month_bcd & 0x0F)
        # day = (day_bcd >> 4) * 10 + (day_bcd & 0x0F)
        # hour = (hour_bcd >> 4) * 10 + (hour_bcd & 0x0F)
        # minute = (minute_bcd >> 4) * 10 + (minute_bcd & 0x0F)

        # textEdit_4g_up_temp_data_result.append(f"时间戳: {year}年{month}月{day}日 {hour}:{minute}")

        # # 输出到文本框
        # self.ui.textEdit_4g_up_temp_data_result.setPlainText("\n".join(textEdit_4g_up_temp_data_result))

        # 解析温度和湿度
        temp_count = data[25]
        start_idx = 26
        data_idx_offset = 9

        for i in range(temp_count):

            # 解析该数据包的时间
            # # 解析时间戳（BCD码）
            year_bcd = data[data_idx_offset * i + start_idx]
            month_bcd = data[data_idx_offset * i + start_idx + 1]
            day_bcd = data[data_idx_offset * i + start_idx + 2]
            hour_bcd = data[data_idx_offset * i + start_idx + 3]
            minute_bcd = data[data_idx_offset * i + start_idx + 4]
            second_bcd = data[data_idx_offset * i + start_idx + 5]

            year = (year_bcd >> 4) * 10 + (year_bcd & 0x0F)
            month = (month_bcd >> 4) * 10 + (month_bcd & 0x0F)
            day = (day_bcd >> 4) * 10 + (day_bcd & 0x0F)
            hour = (hour_bcd >> 4) * 10 + (hour_bcd & 0x0F)
            minute = (minute_bcd >> 4) * 10 + (minute_bcd & 0x0F)
            second = (second_bcd >> 4) * 10 + (second_bcd & 0x0F)

            textEdit_4g_up_temp_data_result.append(
                f"第{i+1}组:时间戳: {year}年{month}月{day}日 {hour}:{minute}:{second}"
            )

            temp_value = (int.from_bytes(
                data[data_idx_offset * i + start_idx+6 : data_idx_offset * i + start_idx+8], byteorder="big", signed=True
            ))/10
            humidity_value = data[data_idx_offset * i + start_idx+8]
            textEdit_4g_up_temp_data_result.append(
                f" 温度={temp_value}°C, 湿度={humidity_value}%"
            )
            #start_idx += 3

        # # 输出到文本框
        self.ui.textEdit_4g_up_temp_data_result.setPlainText("\n".join(textEdit_4g_up_temp_data_result))


if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = protocol_analyze_Widget()
    window.show()

    sys.exit(app.exec_())
